<template>
  <a-input
    v-show="inputShow"
    v-model="value"
    :disabled="disabled"
    placeholder="请选择"
    :allow-clear="allowClear"
    readonly
    class="input-modal"
    @clear.stop="handerClear"
    @search="select"
    @change="inputChange"
  >
    <template #append>
      <div class="apppend-box" @click="select"><icon-more /></div>
    </template>
  </a-input>
  <modal
    v-if="visible"
    :width="'1000'"
    :title="props.title"
    @modal-close="modalClose"
    @open="open"
    @handle-ok="handleOk"
  >
    <div :class="isFullscreen ? screenClass : ''">
      <query-form
        ref="queryFormRef"
        :render-config="config"
        :render-keys="renderKeys"
        @search="searchHandle"
        @reset="resetHandle"
      />
      <table-container
        v-model:columns="renderColumns"
        v-model:is-fullscreen="isFullscreen"
        :loading="isLoading"
        :all-columns="allColumns"
        :show-full-screen="false"
        @refresh="getData"
      >
        <a-table
          :columns="renderColumns"
          :data="renderData"
          :pagination="pagination"
          :loading="isLoading"
          :row-selection="{ type: 'radio' }"
          :row-key="rowId"
          @page-change="pageChange"
          @page-size-change="pageSizeChange"
          @select="selectRow"
        >
          <template #secretLevel="{ record }">
            <secretLevel :record="record" />
          </template>
          <template #empty>
            <div class="table-empty">
              <tableEmpty />
              <div class="empty-description">暂无数据</div>
            </div>
          </template>
          <template #columns>
            <template v-for="item in renderColumns" :key="item.title">
              <a-table-column
                v-if="item.dataIndex === 'secretLevel'"
                header-cell-class="edit-table-header"
                :width="item.width"
                :title="item.title"
              >
                <template #cell="{ rowIndex, record }">
                  <secretLevel
                    :key="rowIndex"
                    :record="record"
                    v-bind="item.componentProps"
                  />
                </template>
              </a-table-column>
              <a-table-column
                v-else
                :title="item.title"
                :ellipsis="true"
                :tooltip="true"
                :width="item?.width"
              >
                <template #cell="{ record }">
                  <span>{{
                    record[item.dataIndex] === 0
                      ? record[item.dataIndex]
                      : record[item.dataIndex]
                      ? record[item.dataIndex]
                      : '-'
                  }}</span>
                </template>
              </a-table-column>
            </template>
          </template>
        </a-table>
      </table-container>
    </div>
  </modal>
</template>

<!--新script-->
<script lang="ts" setup>
  import { computed, onMounted, ref, watch } from 'vue';
  import queryForm from '@/common/components/query-form/index.vue';
  import tableContainer from '@/common/components/table-container/index.vue';
  import request from '@/utils/request/request';
  import usePagination from '@/common/hooks/pagination';
  import lodash from 'lodash';
  import useFullScreen from '@/common/hooks/fullScreen';
  import secretLevel from '@/common/components/secret-level-info/index.vue';
  import { Message } from '@arco-design/web-vue';
  import tableEmpty from '@/common/components/image/tableEmpty.svg?component';
  import { modalCofig } from './input-modal-config';
  import modal from './modal.vue';

  const { isFullscreen, screenClass } = useFullScreen();
  const props = defineProps({
    modelValue: {
      type: [String, Object],
    },
    /**
     * @param {string}
     * 回显值
     */
    labelValue: {
      type: String,
      default: '',
    },
    title: {
      type: String,
      default: '',
    },
    /**
     * @param {string}
     * 绑定数据的对象key
     */
    valueName: {
      type: String,
      default: 'id',
    },
    /**
     * @param {string}
     * input 框的回显字段
     */
    labelName: {
      type: String,
      required: true,
      default: 'name',
    },
    /**
     * 筛选框中哪些数据来源需要做密级筛选
     */
    queryFitSecretLevelKeys: {
      type: Array,
      default: () => {
        return [];
      },
    },
    /**
     * @param {Array}
     * 自定义显示筛选字段
     */
    queryKeys: {
      type: Array,
      default: () => {
        return [];
      },
    },
    /**
     * @param {string}
     * 使用配置文件的类型
     */
    type: {
      type: String,
      required: true,
      default: '',
    },
    allowClear: {
      type: Boolean,
      default: true,
    },
    defaultQuery: {
      type: Object,
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      default: () => {},
    },
    showTips: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    inputShow: {
      type: Boolean,
      default: true,
    },
    callback: {
      type: Function,
    },
  });
  const { pagination, setCurrent, setPageSize, setTotal, queryPagination } =
    usePagination();
  const renderColumns = ref<any[]>([]); // 最终渲染的列
  const queryFormRef = ref();
  const selectedRow: any = ref({});
  const renderKeys = ref<any>([]);
  const rowId = ref('id');
  watch(
    () => props.type,
    (n: string) => {
      if (modalCofig[n]?.rowKey) {
        rowId.value = modalCofig[n]?.rowKey;
      }
    },
    {
      deep: true,
      immediate: true,
    }
  );

  const config = computed(() => {
    const { renderConfig } = modalCofig[props.type];
    if (props.defaultQuery && props.defaultQuery.constructor === Object) {
      Object.keys(props.defaultQuery).forEach((key) => {
        Object.keys(renderConfig).forEach((configKey) => {
          if (key === renderConfig[configKey].field) {
            renderConfig[configKey].value = props.defaultQuery[key];
          }
        });
      });
    }

    lodash.forEach(props.queryFitSecretLevelKeys, (val: any) => {
      if (renderConfig[val]) {
        renderConfig[val].componentProps = {
          ...(renderConfig[val].componentProps || {}),
        };
        renderConfig[val].componentProps.defaultQuery = {
          ...(renderConfig[val].componentProps.defaultQuery || {}),
        };
        renderConfig[val].componentProps.defaultQuery.secretLevel =
          props.defaultQuery.secretLevel;
      }
    });
    return renderConfig;
  });
  const columns = computed(() => {
    return modalCofig[props.type].columns;
  });
  const allColumns = lodash.cloneDeep(columns);
  const emit = defineEmits([
    'update:modelValue',
    'change',
    'handerClear',
    'select',
    'handleOk',
    'showTips',
  ]);
  const visible = ref(false);
  const value = ref(props.labelValue);
  watch(
    () => props.queryKeys,
    (n: any) => {
      renderKeys.value.length = 0;
      if (n?.length > 0) {
        renderKeys.value = [...n];
      } else {
        renderKeys.value = [...modalCofig[props.type].renderKeys];
      }
    },
    { deep: true, immediate: true }
  );
  watch(
    () => props.labelValue,
    (n: any) => {
      value.value = n;
    },
    { deep: true, immediate: true }
  );
  watch(
    () => props.modelValue,
    (n: any) => {
      if (!n) {
        value.value = n;
      }
    },
    { deep: true, immediate: true }
  );
  onMounted(() => {
    renderColumns.value = columns.value;
  });
  const select = () => {
    if (props.disabled) {
      emit('showTips');
      return;
    }
    if (props.showTips) {
      Message.warning(props.showTips);
      return;
    }
    visible.value = true;
  };
  const handerClear = () => {
    emit('update:modelValue', null);
    emit('change');
    emit('handerClear');
  };
  const modalClose = () => {
    selectedRow.value = {};
    visible.value = false;
  };
  const selectRow = (keys: any, key: any, record: any) => {
    emit('select', record);
    selectedRow.value = record || {};
  };
  const searchHandle = () => {
    setCurrent(1);
    getData();
  };
  const resetHandle = () => {
    setCurrent(1);
    getData();
  };
  const inputChange = () => {
    emit('change');
  };
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);

  const getData = async () => {
    const params = {
      ...queryFormRef.value.getStatus(),
      ...queryPagination.value,
      ...props.defaultQuery,
    };
    renderData.value = [];
    isLoading.value = true;
    const { data } = await request.get(modalCofig[props.type].api, { params });
    renderData.value = data.list || data;
    setTotal(data.total);
    isLoading.value = false;
  };
  const pageChange = (val: number) => {
    setCurrent(val);
    getData();
  };
  const pageSizeChange = (val: number) => {
    setPageSize(val);
    getData();
  };
  const handleOk = () => {
    value.value = selectedRow.value[props.labelName];
    emit('change');
    emit('update:modelValue', selectedRow.value[props.valueName]);
    emit('handleOk', lodash.cloneDeep(selectedRow.value));
    if (props.callback) {
      props.callback(lodash.cloneDeep(selectedRow.value));
    }
  };
  const open = () => {
    getData();
  };

  defineExpose({ select });
</script>

<style lang="less" scoped>
  .base-component {
    color: red;
  }
  .table-empty {
    box-sizing: border-box;
    width: 100%;
    padding: 10px 0;
    text-align: center;
  }
  .apppend-box {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .arco-input-outer.arco-input-outer-disabled {
    :deep(.arco-input-append) {
      cursor: not-allowed;
      background-color: var(--color-fill-2);
    }
  }
</style>
